package com.papper.mng.controller.sys;

import com.google.common.collect.Lists;
import com.papper.common.bean.sys.SysCode;
import com.papper.common.config.LocalConfig;
import com.papper.common.config.SysCodeHelp;
import com.papper.common.config.SysConfigHelp;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.exception.ServiceException;
import com.papper.common.service.sys.SysCodeService;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.controller.BaseAction;
import com.papper.mng.domain.DwzResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/sys/code")
public class SysCodeAction extends BaseAction {
    @Autowired
    SysCodeService sysCodeService;

    /**
     * 系统字典
     *
     * @return
     */
    @GetMapping(value = "")
    public String execute(Model model, Long pid, String sv) {
        // 顶级字典
        Example          example  = new Example(SysCode.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId", 0);
        if (!StringTool.isEmpty(sv)) {
            criteria.andLike("codeKey", "%" + StringTool.nullToEmpty(sv) + "%");
        }
        example.setOrderByClause("code_sort asc");
        List<SysCode> codes  = sysCodeService.find(example);
        SysCode       parent = sysCodeService.findById(pid);
        if (parent == null && codes == null) {
            return render("sys/code/index");
        }
        if (parent == null && codes.size() > 0) {
            parent = codes.get(0);
        } else if (parent != null && parent.getParentId().intValue() != 0) {
            parent = codes.get(0);
        }
        if (parent == null || codes == null) {
            return render("sys/code/index");
        }
        model.addAttribute("codes", codes);
        model.addAttribute("parent", parent);
        model.addAttribute("pid", parent.getId());
        model.addAttribute("sv", StringTool.nullToEmpty(sv));
        // 字典配置信息
        List<SysCode> childCodes = sysCodeService.findByParentId(parent.getId());
        model.addAttribute("childCodes", childCodes);
        return render("sys/code/index");
    }

    @RequestMapping(value = "/suggest")
    @ResponseBody
    public List<SysCode> suggest(String key) {
        SysCode sysCode = sysCodeService.findByKey(key);
        if (sysCode == null) {
            return Lists.newArrayList();
        }
        List<SysCode> list = sysCodeService.findByParentId(sysCode.getId());
        return list;
    }

    @RequestMapping(value = "/accountType")
    @ResponseBody
    public List<List<String>> accountType(String accountType) {
        // 字段查询条件
        List<List<String>> rtn   = Lists.newArrayList();
        List<String>       items = Lists.newArrayList();
        if (StringUtil.isEmpty(accountType)) {
            items = Lists.newArrayList();
            items.add("");
            items.add("--请选择级别--");
            rtn.add(items);
            return rtn;
        }
        SysCode sysCode = null;
        if ("1".equals(accountType)) {
            sysCode = sysCodeService.findByKey("OrgType");
            if (sysCode == null) {
                items = Lists.newArrayList();
                items.add("");
                items.add("--请选择级别--");
                rtn.add(items);
                return rtn;
            }
            List<SysCode> list = sysCodeService.findByParentId(sysCode.getId());
            if (list == null || list.isEmpty()) {
                items = Lists.newArrayList();
                items.add("");
                items.add("--请选择级别--");
                rtn.add(items);
            } else {
                for (SysCode sysCode1 : list) {
                    items = Lists.newArrayList();
                    items.add(sysCode1.getCodeKey());
                    items.add(sysCode1.getCodeValue());
                    rtn.add(items);
                }
            }
        } else if ("2".equals(accountType)) {
            items = Lists.newArrayList();
            items.add("L98");
            items.add("通道外放");
            rtn.add(items);
            items = Lists.newArrayList();
            items.add("L99");
            items.add("终端商户");
            rtn.add(items);
        } else {
            items = Lists.newArrayList();
            items.add("");
            items.add("--请选择级别--");
            rtn.add(items);
            return rtn;
        }
        return rtn;
    }

    /**
     * 系统字典
     *
     * @return
     */
    @RequestMapping(value = "/child")
    public String child(Model model, Long pid) {
        SysCode parent = sysCodeService.findById(pid);
        model.addAttribute("parent", parent);
        List<SysCode> codes = sysCodeService.findByParentId(pid);
        model.addAttribute("codes", codes);
        return render("sys/code/child");
    }

    /**
     * 系统字典_新增
     *
     * @param _response
     * @param pid
     * @
     */
    @GetMapping(value = "/add")
    public String add_get(HttpServletResponse _response, Model model, Long pid) {
        model.addAttribute("nick", getNick());
        if (pid == 0) {
            model.addAttribute("pid", pid);
            model.addAttribute("pname", "顶级字典");
        } else {
            SysCode parent = sysCodeService.findById(pid);
            model.addAttribute("pid", pid);
            model.addAttribute("pname", parent.getCodeKey());
        }
        return render("sys/code/add");
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public DwzResponse add_post(HttpServletRequest _request, SysCode sysCode) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (sysCode == null) {
            return new DwzResponse("300", "参数[sysCode]异常！");
        }
        SysCode dbCode = sysCodeService.findByKey(sysCode.getCodeKey(), sysCode.getParentId().longValue());
        if (dbCode != null) {
            return new DwzResponse("300", "该值已存在！");
        }
        try {
            sysCode.setDataStatus(DataStatusEnum.OPEN.getCode());
            sysCodeService.save(sysCode);
            return new DwzResponse("200", "系统字典添加成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统字典添加失败:" + e.getMessage() + "!!!");
        }
    }

    /**
     * 系统字典_更新
     *
     * @param _response
     * @param id
     * @
     */
    @GetMapping(value = "/edit")
    public String edti_get(HttpServletResponse _response, Model model, Long id) {
        SysCode entity = sysCodeService.findById(id);
        model.addAttribute("entity", entity);
        model.addAttribute("nick", getNick());
        return render("sys/code/edit");
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public DwzResponse edit_post(HttpServletRequest _request, SysCode sysCode) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (sysCode == null || sysCode.getId() == null) {
            return new DwzResponse("300", "参数[sysCode]异常！");
        }
        try {
            sysCodeService.update(sysCode);
            return new DwzResponse("200", "系统字典修改成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统字典修改失败:" + e.getMessage());
        }
    }

    /**
     * 系统字典_删除
     *
     * @param id
     * @
     */
    @PostMapping(value = "/del")
    @ResponseBody
    public DwzResponse del_post(HttpServletRequest _request, Long id) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        if (id == null || id.intValue() <= 0) {
            return new DwzResponse("300", "参数[id]异常！");
        }
        try {
            sysCodeService.deleteById(id);
            return new DwzResponse("200", "系统字典删除成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
            return new DwzResponse("300", "系统字典修改失败:" + e.getMessage());
        }
    }

    /**
     * 系统字典_详情
     *
     * @return
     */
    @GetMapping(value = "/detail")
    public String detail(HttpServletResponse _response, Model model, Long id) {
        SysCode sysCode = sysCodeService.findById(id);
        model.addAttribute("entity", sysCode);
        return render("sys/code/detail");
    }

    /**
     * 系统字典_刷新缓存
     *
     * @
     */
    @PostMapping(value = "/flush")
    @ResponseBody
    public DwzResponse flush_post(HttpServletRequest _request) {
        try {
            checkSuperCert(_request);
        } catch (ServiceException e) {
            return new DwzResponse("300", e.getMessage());
        }
        SysConfigHelp.I().initPropertys();
        SysCodeHelp.I().initPropertys();
        LocalConfig.I().initPropertys();
        //TODO-关联刷新
        //                redisCacheMqService.producerEvent("MqConfigFlush", "1");
        return new DwzResponse("200", "系统字典刷新成功!!!");
    }
}
